package com.pencilisland.pay.mgt.console.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pencilisland.pay.mgt.console.entity.SysOrg;
import com.pencilisland.pay.mgt.console.entity.SysRole;
import com.pencilisland.pay.mgt.console.entity.SysUser;
import com.pencilisland.pay.mgt.console.service.OrgService;
import com.pencilisland.pay.mgt.console.service.RoleService;
import com.pencilisland.pay.mgt.console.service.UserService;
import com.pencilisland.pay.mgt.util.G;

@Component
public class ShiroDbRealm extends AuthorizingRealm {

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	OrgService orgService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		String loginName = G.str(principals.getPrimaryPrincipal());

		log.debug("用户[{}]角色", loginName);

		ShiroUser loginUser = userService.findByLoginName(loginName);

		SysUser user = (SysUser) loginUser.getRealUser();

		List<SysOrg> orgList = orgService.findAllParentOrg(user);

		List<SysRole> roles = roleService.findAllRoles(user, orgList);

		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

		if (roles != null && !roles.isEmpty()) {
			for (SysRole role : roles) {
				authorizationInfo.addRole(role.getRoleKey());
			}
		}

		return authorizationInfo;

	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		String loginName = G.str(token.getPrincipal());
		log.debug("用户[{}]验证", loginName);

		ShiroUser loginUser = userService.findByLoginName(loginName);

		if (loginUser == null) {
			throw new UnknownAccountException();
		}

		if (loginUser.isDisabled()) {
			throw new DisabledAccountException();
		}

		ByteSource salt = ByteSource.Util.bytes(loginUser.getSaltBytes());

		return new SimpleAuthenticationInfo(loginName, loginUser.getPassword(), salt, getName());
	}

}
